﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;

namespace MyAMS.WebServer.Infrastructure
{
    internal sealed class ControllerFactory : DefaultControllerFactory
    {
        private readonly IUnityContainer container;

        public ControllerFactory(IUnityContainer container)
        {
            this.container = container;
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType != null) //TODO (5he11) 这里应该断言一下, 然后给个友好提示
            {
                IController icontroller = container.Resolve(controllerType) as IController;
                if (typeof(Controller).IsAssignableFrom(controllerType))
                {
                    Controller controller = icontroller as Controller;

                    if (controller != null)
                    {
                        controller.ActionInvoker = container.Resolve<IActionInvoker>();
                    }
                    return icontroller;
                }

                return icontroller;
            }
            return null;
        }
    }
}
